<template>
  <div>
    <page-main>
      <el-row>
        <el-col :span="6">
          <span style="margin-right: 10px">设备类型:</span>
          <el-select v-model="searchForm.mold_id" filterable clearable placeholder="请选择">
            <el-option v-for="item in moldType" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <span style="margin-right: 10px">状态:</span>
          <el-select v-model="searchForm.status" filterable clearable placeholder="请选择">
            <el-option v-for="item in status" :key="item.id" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <span style="margin-right: 10px">设备编号:</span>
          <el-input clearable v-model="searchForm.device_no" class="input" placeholder="请输入"></el-input>
        </el-col>
        <el-col :span="6">
          <span style="margin-right: 10px">更新时间:</span>
          <el-date-picker
            v-model="updata_times"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="x"
          >
          </el-date-picker>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" style="margin-left: 10px" @click="searchBtn">搜索</el-button>
          <el-button type="warning" @click="refreshBtn">重置</el-button>
        </el-col>
      </el-row>
    </page-main>
    <page-main>
      <el-table :data="tableData" border :default-sort="{ prop: 'id', order: 'descending' }">
        <el-table-column label="设备类型" prop="mold_name"></el-table-column>
        <el-table-column label="设备名称" prop="device_name"></el-table-column>
        <el-table-column label="安装位置" prop="address"> </el-table-column>
        <el-table-column label="设备编号" prop="device_no"></el-table-column>
        <el-table-column label="设备状态" prop="status">
          <template #default="scope">
            <div
              :style="
                scope.row.status == 2
                  ? 'color:orange'
                  : scope.row.status == 5
                  ? 'color:red'
                  : scope.row.status == 6
                  ? 'color:#ccc'
                  : scope.row.status == 3
                  ? 'color:orange'
                  : ''
              "
            >
              {{ ['', '正常', '预警', '故障', '停用', '报警', '离线'][scope.row.status] }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="预警值" prop="warn_data">
          <template #default="scope">
            <div v-for="(item, index) in scope.row.warn_data" :key="index">
              {{ item.title + '：' + item.value }}
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="量值">
          <template #default="scope">
            <span v-html="scope.row.measure" v-if="scope.row.measure"></span>

          </template>
        </el-table-column> -->
        <el-table-column label="更新时间" prop="update_time" :formatter="getDateTime"></el-table-column>
        <el-table-column label="操作" fixed="right">
          <template #default="scope">
            <div>
              <el-button type="info" @click="showDetail(scope.row)" size="mini">查看历史</el-button>
            </div>
            <div style="margin-top: 10px">
              <!-- <el-button
                v-if="scope.row.name_id == 157 || scope.row.mold_id == 30"
                type="danger"
                size="mini"
                @click="playVideoEvent(scope.row)"
                >视频监控</el-button
              > -->
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @current-change="handleCurrentChange"
          v-model:currentPage="tableDataInfo.page"
          :page-count="tableDataInfo.total_page"
          :total="tableDataInfo.total"
          background
          layout="total,prev, pager, next, jumper"
        >
        </el-pagination>
      </div>
      <!-- 详情 start -->
      <el-dialog
        v-model="showDetailsDialog"
        v-if="showDetailsDialog"
        width="70%"
        @close="closeDetailsDialog"
        :close-on-click-modal="false"
      >
        <el-tabs v-model="activeName" type="card" class="demo-tabs" @click="handleClick">
          <el-tab-pane label="详情" name="detail"></el-tab-pane>
          <el-tab-pane label="设备上报记录" name="report"></el-tab-pane>
        </el-tabs>
        <div v-if="activeName === 'detail'">
          <deviceReportShow :details="details" :isAll="true"></deviceReportShow>
        </div>
        <div v-else class="report-wrapper">
          <el-table :data="historyTabletableData" border style="width: 100%">
            <el-table-column prop="device_no" label="设备编号"> </el-table-column>
            <el-table-column label="事件">
              <template #default="scope">
                <div v-html="scope.row.event_type"></div>
              </template>
            </el-table-column>
            <!-- <el-table-column label="量值">
              <template #default="scope">
                <span v-html="scope.row.measure" v-if="scope.row.measure"></span>
              </template>
            </el-table-column> -->
            <el-table-column prop="create_time" label="开始时间">
              <template #default="scope">{{ $getDateTime(scope.row.create_time) }}</template>
            </el-table-column>
            <!-- <el-table-column label="操作">
                    <template #default="scope">
                        <el-button
                        v-if="scope.row.exec_remark != '设备离线'"
                        type="primary"
                        @click="innerShowDetail(scope.row)"
                        size="mini"
                        >详情</el-button>
                    </template>
                </el-table-column> -->
          </el-table>
        </div>
        <div v-if="activeName === 'report'" class="block report">
          <el-pagination
            style="width: 100%; text-align: center"
            @current-change="getHistoryInfoList"
            v-model:currentPage="historyTableDataInfo.page"
            :page-count="historyTableDataInfo.total_page"
            :total="historyTableDataInfo.total"
            background
            layout="total,prev, pager, next, jumper"
          >
          </el-pagination>

          <div ref="trenChart" style="width: 100%; height: 50vh"></div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closeDetailsDialog">返 回</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 详情 end -->
      <!-- 详情 start -->
      <el-dialog
        v-model="innerShowDetailsDialog"
        v-if="innerShowDetailsDialog"
        width="70%"
        @close="closeInnerDetailsDialog"
        :close-on-click-modal="false"
      >
        <deviceReportShow :details="innerdetails" :isAll="true"></deviceReportShow>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="innerShowDetailsDialog = false">返 回</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 详情 end -->
      <el-dialog v-model="playVideoBoxDialog" width="50%" destroy-on-close class="detailsDialog">
        <!-- <iframe
        :src="playingVideoUrl"
        style="width: 100%; height: 50vh"
        frameborder="0"
      >

      </iframe> -->
        <div style="width: 100%; height: 50vh">
          <iframe id="dplayer" :src="playingVideoUrl" style="width: 100%; height: 100%"></iframe>
        </div>
      </el-dialog>
    </page-main>
  </div>
</template>

<script>
//引入 hls与dplayer 用于解析播放视频
import Hls from 'hls.js'
import Dplayer from 'dplayer'
import { useRouter } from 'vue-router'
import { setDeviceData } from '@/util/deviceData'

import { markRaw } from 'vue'

import { ref, onMounted } from 'vue'
// 标识组件
import deviceReportShow from './deviceReportShow.vue'

// import {ref} from 'vue'
export default {
  props: ['rows', 'deviceStatus'],
  components: {
    deviceReportShow
  },
  data() {
    return {
      shows: false,
      activeName: 'detail',
      reportList: [],
      tableData: [],
      tableDataInfo: '',
      moldType: [],
      updata_times: '',
      searchForm: {
        mold_id: '',
        status: this.deviceStatus,
        start_update_time: '',
        end_update_time: ''
      },
      status: [
        // 1. 正常，2.预警，3.故障,4.停用，5报警，6-不在线 7-在线
        { label: '正常', value: 1 },
        { label: '预警', value: 2 },
        { label: '故障', value: 3 },
        { label: '停用', value: 4 },
        { label: '报警', value: 5 },
        { label: '离线', value: 6 },
        { label: '在线', value: 7 }
      ],
      defaultProps: {
        children: 'sub_item',
        label: 'name',
        value: 'id',
        checkStrictly: true
      },
      historyInfoDialog: false,
      historyTabletableData: [],
      historyTableDataInfo: '',
      device_no: '',
      device_method: '',
      showDetailsDialog: false,
      innerShowDetailsDialog: false,
      details: {},
      playingVideoUrl: '',
      playVideoBoxDialog: false,
      trenChart: '',
      aqwe: ''
    }
  },
  mounted() {
    this.getDeviceLists()
    // this.rendertrenChart()
  },
  created() {
    this.getMoldType()
  },
  methods: {
    rendertrenChart() {
      // this.trenChart = markRaw(Echarts.init(this.$refs.trenChart))
      let data = this.historyTabletableData
      let dateData = []
      let seriesDataArr = []
      let seriesDataArrName = []
      let seriesData = []
      let series = []
      data.map((item) => {
        seriesDataArr = item.measure.split('<br />')
        seriesDataArr.map((item2) => {
          if (item2.length) {
            if (seriesDataArrName.indexOf(item2.split(':')[0]) == -1) {
              seriesDataArrName.push(item2.split(':')[0])
              series.push({
                name: item2.split(':')[0],
                type: 'line',
                stack: 'Total',
                data: []
              })
            }
            seriesData.push({
              name: item2.split(':')[0],
              data: item2.split(':')[1],
              company: item2.split(':')[1].replace(/[^a-zA-Z]/g, '')
            })
          }
        })
        dateData.push(this.$getDateTime(item.update_time))
      })
      series.map((item) => {
        seriesData.map((item2) => {
          if (item.name == item2.name) {
            item.data.push({
              value: parseFloat(item2.data),
              company: item2.company
            })
          }
        })
      })
    },

    playVideoEvent(row) {
      this.$api.post('/unit/DeviceInstall/showDevice', { device_no: row.device_no }).then((res) => {
        // if (res.data.name_id == 167) {

        // } else {
        //   this.playingVideoUrl = video_url;

        //   this.playVideoBoxDialog = true;
        // }

        let { video_url } = res.data
        if (!video_url) {
          this.$message.error('视频连接错误，请稍后再试')
          return false
        }
        console.log(res.data)
        this.playingVideoUrl = video_url
        if (res.data.factory_name == '萤石云' || res.data.factory_name == '智城') {
          this.playVideoBoxDialog = true
        } else if (res.data.installer == '赋安云' || res.data.factory_name == '海康') {
          this.$router.push({
            name: 'video',
            query: {
              data: video_url
            }
          })
        }
      })
    },
    handleClick() {
      if (this.activeName === 'report') {
        this.getHistoryInfoList()
      }
      if (this.activeName === 'report') {
      }
    },
    closeDetailsDialog() {
      this.activeName = 'detail'
      this.showDetailsDialog = false
    },
    innerShowDetail(row) {
      this.innerdetails = row
      this.innerShowDetailsDialog = true
      this.ondetailShow(row)
    },
    showDetail(row) {
      this.details = row
      this.showDetailsDialog = true
      this.ondetailShow(row)
    },
    ondetailShow(row) {
      this.device_no = row.device_no
      let new_device_data = row.device_method
      if (new_device_data == '4gWirelessPressure') {
        new_device_data = 'fgWirelessPressure'
      }
      if (new_device_data == '4gWirelessLiquidLevel') {
        new_device_data = 'fgWirelessLiquidLevel'
      }
      this.device_method = new_device_data
    },
    formatterTime(row, column, cellValue, index) {
      return this.$getDateTime(cellValue)
    },
    showHistoryInfo(row) {
      this.historyInfoDialog = true
      this.device_no = row.device_no
      this.getHistoryInfoList()
    },
    async getHistoryInfoList(page) {
      let pageNum = 1
      if (page) {
        pageNum = page
      }
      let resp = await this.$api.post('/unit/DeviceWarning/Lists', {
        page: pageNum,
        rows: 6,
        device_no: this.device_no,
        device_method: 1
      })
      this.historyTabletableData = await setDeviceData(resp.data.list)
      // this.rendertrenChart()
      delete resp.data.list
      this.historyTableDataInfo = resp.data
      let chartRes = await this.$api.post('/unit/DeviceLog/Trend', {
        time_begin: '',
        time_end: '',
        device_no: this.device_no
      })
      // this.trenchartData = await setDeviceData(chartRes.data.list);
      // console.log(this.trenchartData);
    },
    //   搜索
    searchBtn() {
      this.getDeviceLists()
    },
    // 重置
    refreshBtn() {
      this.searchForm = {
        mold_id: '',
        status: '',
        start_update_time: '',
        end_update_time: ''
      }
      this.getDeviceLists()
    },
    getDateTime(row, column, cellValue, index) {
      return this.$getDateTime(cellValue)
    },
    deviceStatus(row, column, cellValue, index) {
      let temp = ['', '正常', '预警', '故障', '停用', '报警', '离线']
      return temp[cellValue]
    },
    handleCurrentChange(e) {
      this.getDeviceLists(e)
    },
    async getDeviceLists(page) {
      let pageNum = 1
      if (page) {
        pageNum = page
      }
      let searchParams = JSON.parse(JSON.stringify(this.searchForm))
      if (this.updata_times) {
        searchParams.start_update_time = this.updata_times[0] / 1000
        searchParams.end_update_time = this.updata_times[1] / 1000 + 86400
      }
      let params = {
        page: pageNum,
        rows: this.rows ? this.rows : 13,
        ...searchParams
      }
      let resp = await this.$api.post('/unit/DeviceInstall/Lists', params)
      this.tableData = await setDeviceData(resp.data.list)

      this.tableDataInfo = resp.data
    },
    // 设备类型
    getMoldType() {
      this.$api.get('/unit/DeviceBase/moldTree').then((res) => {
        this.moldType = res.data
      })
    }
  }
}
</script>

<style scoped lang="scss">
.block {
  display: block;
  // justify-content: center;
  // align-items: center;
  margin-top: 20px;
}
.el-col {
  display: flex;
  white-space: nowrap;
  align-items: center;
}
:deep(.el-range-separator) {
  width: 30px;
}
:deep(.el-scrollbar__wrap) {
  overflow: hidden;
}
.report-wrapper {
  max-height: 530px;
  overflow-x: hidden;
  overflow-y: auto;
  .device-report-list {
    height: auto !important;
    max-height: 50vh;
    margin-bottom: 20px;
  }
}
</style>
